package com.bristua.mall.admin.common.interceptor;
import com.bristua.mall.admin.common.bean.Result;
import com.bristua.mall.admin.common.enums.CommonCode;
import com.bristua.mall.admin.common.utils.CacheUtil;
import com.bristua.mall.admin.common.utils.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class UserLoginHandlerInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(UserLoginHandlerInterceptor.class);

    @Autowired
    private CacheUtil cacheUtil;


    private Object getUserInfo(HttpServletRequest request){
        String token = getToken(request);
        return cacheUtil.get(token);
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String url = request.getRequestURI();
        if (url.contains("admin") && !url.contains("login")){
            Result result = new Result();
            String token = getToken(request);
            if (!StringUtils.isEmpty(token)) {
                Object  userinfo = getUserInfo(request);
                if (null != userinfo) {
                    return true;
                }else{
                    result.setCode(CommonCode.SESSION_EXPIR.getCode());
                    result.setMsg(CommonCode.SESSION_EXPIR.getMsg());
                    render(response, JsonUtil.toJson(result));
                }
            }
            result.setCode(CommonCode.SESSION_FAIL.getCode());
            result.setMsg(CommonCode.SESSION_FAIL.getMsg());
            //text/html;charset=UTF-8
            render(response,JsonUtil.toJson(result));

            return false;

        }
        return true;

    }


    private String getToken(HttpServletRequest request) {

        String t = request.getParameter("token");
        if (t != null) {
            return t;
        }
        t = request.getHeader("token");
        if (t != null) {
            return t;
        }


        return null;
    }

    private String getThird(HttpServletRequest request) {

        String t = request.getParameter("third");
        if (t != null) {
            return t;
        }
        t = request.getHeader("third");
        if (t != null) {
            return t;
        }

        return null;
    }


    private String render(HttpServletResponse response, String text) {
        try {
            response.setHeader("Cache-Control", "no-cache");
            response.setContentType("text/json;charset=UTF-8");
            response.getWriter().write(text);
            response.getWriter().flush();
            response.getWriter().close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }




    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o, ModelAndView model) throws Exception {
        // TODO Auto-generated method stub
        String path = request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
        if (null != model && null != model.getModel()) {
            model.addObject("basePath", basePath);
            model.addObject("user", getUserInfo(request));
        }




//        if (!flag) {
//            Map postParams = getPostParams(request);
//            if (postParams != null) {
//                if (postParams.get("startTime") != null) {
//                    request.getSession().setAttribute("startTime", postParams.get("startTime") + "");
//                }
//                if (postParams.get("endTime") != null) {
//                    request.getSession().setAttribute("endTime", postParams.get("endTime") + "");
//                }
//                if (postParams.get("kssj") != null) {
//                    request.getSession().setAttribute("startTime", postParams.get("kssj") + "");
//                }
//                if (postParams.get("jssj") != null) {
//                    request.getSession().setAttribute("endTime", postParams.get("jssj") + "");
//                }
//            }
//
//        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {

    }

}
